# -*- coding: utf-8 -*-

import logging
from PyQt4 import QtCore, QtGui
from configobj import ConfigObj
from gui.ui_pyBook import Ui_pyBookGUI
from gui.guiThreads.coverSeeker import CoverSeeker
from gui.guiThreads.bookSeeker import BookSeeker

class PyBookGUI(QtGui.QMainWindow, Ui_pyBookGUI):
    def __init__(self, parent=None):
        super(PyBookGUI,self).__init__(parent)
        frame = QtGui.QFrame(self)
        self.setCentralWidget(frame)
        self.setupUi(frame)
        self.statusBar().showMessage("Bienvenido a pyBook")
        self.bookLanguages={
            'eng':QtCore.QString(u'Inglés'),
            'spa':QtCore.QString(u'Español'),
            'ita':QtCore.QString(u'Italiano'),
            'ger':QtCore.QString(u'Alemán'),
            'fre':QtCore.QString(u'Francés')}


        # Initial configuration
        self.index = 0
        self.moreEnable = False
        self.forMoreResults = False
        self.listaLibrosActual = {}
        self.lock = QtCore.QReadWriteLock()
        self.coverSeekers = set()
        self.bookSeekers = set()

        # Get portadas dir
        self.config = ConfigObj('conf/pyBook.conf')
        icon = self.config['icon_file']
        covers_dir = self.config['covers_dir']
        self.default_cover = covers_dir + self.config['default_cover']
        self.actual_cover = self.default_cover
#        logging.info(icon)
        self.setWindowIcon(QtGui.QIcon(icon)) # TODO: No esta funcionando

        self.connect(self.buscar, QtCore.SIGNAL('clicked()'),
            self.searchBook)

        self.connect(self.masResultados, QtCore.SIGNAL('clicked()'),
            self.moreResults)

        self.connect(self.salir, QtCore.SIGNAL('clicked()'),
            QtGui.qApp, QtCore.SLOT('quit()'))

        self.connect(self.listaLibros, QtCore.SIGNAL('itemSelectionChanged()'),
            self.updateBookInfo)

    def setModel(self, bookMan):
        logging.debug("Setting model")
        self.bookMan = bookMan

    def searchBook(self):
        self.moreEnable = True
        self.forMoreResults = False
        msg = "Buscando libro por %s: %s" % \
            (self.campoBusqueda.currentText(), self.valorBusqueda.text())
        self.statusBar().showMessage(msg)
        self.repaint()
        logging.info(msg)
        self.numeroLibros.setText("0")

        self.lastIndex = self.campoBusqueda.currentText()
        self.lastValue = self.valorBusqueda.text()
        self.__startBookSeeker(self.campoBusqueda.currentText(),
            self.valorBusqueda.text())

    def moreResults(self):
        msg = "Buscando libro por %s: %s" % \
            (self.campoBusqueda.currentText(), self.valorBusqueda.text())
        self.forMoreResults = True
        self.statusBar().showMessage(msg)
        self.repaint()
        if not self.moreEnable:
            self.statusBar().showMessage(u"No se ha realizado ninguna búsqueda")
        else:
            self.__startBookSeeker(self.lastIndex, self.lastValue, True)

    def updateView(self):
        if not self.listaLibrosActual.values() == self.bookMan.get_book_list():
            if not self.forMoreResults:
                self.listaLibros.clear()
                self.listaLibrosActual = {}
                self.index = 0
                
            for book in self.bookMan.get_book_list()[self.index:]:
                title = QtCore.QString(book.get_title())
                item = QtGui.QListWidgetItem(title, self.listaLibros)
                item.setToolTip(title)
                self.listaLibros.addItem(item)
                self.listaLibros.repaint()
                self.listaLibrosActual[self.index] = book
                self.index +=1
                self.numeroLibros.setText(str(self.index))
            self.__startCoverSeeker(self.bookMan.get_book_list())

    def updateBookInfo(self):
        row = self.listaLibros.currentRow()
        logging.info("Updating book info: %s" % row)
        book = self.listaLibrosActual[row]

        self.__setTitle(book.title)

        if book.get_long_title():
            self.tituloLargo.setToolTip(book.get_long_title())
            if (len(book.get_long_title()) > 70):
                self.tituloLargo.setText(book.get_long_title()[:67] + "...")
            else:
                self.tituloLargo.setText(book.get_long_title())

        self.__setLabelValueText(self.autor_val,book.get_authors())
        self.__setLabelValueText(self.editor_val, book.get_publisher())
        self.__setLabelValueText(self.edicion_val, book.get_edition_info())
        self.__setLabelValueText(self.descripcion_val, book.get_summary())
        self.__setLabelValueText(self.descripcion_f_val, book.get_physical_description())
        self.__setLabelValueText(self.descripcion_val, book.get_summary())
        self.__setLabelValueText(self.temas_val, "\n".join(book.get_subjects()))
        self.__setLabelValueText(self.isbn_val, book.get_isbn())

        if (book.get_language() is not None and len(book.get_language())>1):
            self.__setLabelValueText(self.lenguaje_val, self.bookLanguages[book.get_language()])
        else:
            self.__setLabelValueText(self.lenguaje_val, "")

        self.actual_cover = book.get_cover()
        self.__setCover()

    def resizeEvent(self, event=None):
        event.accept()
        self.__setCover()

    def __setCover(self):
        self.repaint()
        pixmap = QtGui.QImage(self.actual_cover)
        if (pixmap.size().height() < 10):
            pixmap = QtGui.QImage(self.default_cover)

        pixmap = pixmap.scaled(self.portada.size(), QtCore.Qt.KeepAspectRatio)
        self.portada.setPixmap(QtGui.QPixmap.fromImage(pixmap))

    def __setTitle(self, title):
        title_long = len(title)
        # Set the point size
        self.titulo.setToolTip("")
        if (title_long > 60):
            self.titulo.setToolTip(title)
            title = title[:58] + "..."
            point_size =13
        elif (title_long > 50):
            point_size = 13
        elif (title_long > 40):
            point_size = 16
        elif (title_long > 30):
            point_size = 17
        elif (title_long > 20):
            point_size = 18
        else:
            point_size = 20

        # Set the font
        font = QtGui.QFont()
        font.setFamily("LMRoman9")
        font.setPointSize(point_size)
        font.setItalic(True)
        self.titulo.setFont(font)
        self.titulo.setText(title)

    def __setLabelValueText(self, label, summary):
        try:
            label.setText(summary)
        except:
            label.setText(u"No disponible")

    def __startCoverSeeker(self, bookList):
        cseeker = CoverSeeker(self.bookMan, self.lock, bookList)
        cseeker.start()
        self.connect(cseeker, QtCore.SIGNAL("downloadCover(QString, QString)"),
            self.setCoverDownloadStatus)
        self.coverSeekers.add(cseeker)

    def __startBookSeeker(self, index, value, moreBooks=False):
        bseeker = BookSeeker(self.bookMan, self.lock, index, value, moreBooks)
        bseeker.start()
        self.connect(bseeker, QtCore.SIGNAL("finishDownloadBooks()"),
            self.setBookDownloadFinish)
        self.bookSeekers.add(bseeker)

    def setCoverDownloadStatus(self, bookIndex, bookTotal):
        if (bookIndex == bookTotal):
            msg = u"Completado"
        else:
            msg = u"Descagado portada %s de %s" % (bookIndex, bookTotal)
        self.statusBar().showMessage(msg)

    def setBookDownloadFinish(self):
        self.statusBar().showMessage(u"Completado")
        self.updateView()

    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_Return:
            self.searchBook()        
